/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.zkex.simple;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.type.FieldVo;
import cn.easyplatform.web.ext.Assignable;
import cn.easyplatform.web.ext.Labelable;
import cn.easyplatform.web.ext.Widget;
import cn.easyplatform.web.ext.zul.Checkgroup;
import cn.easyplatform.web.task.OperableHandler;
import cn.easyplatform.web.task.zkex.ListSupport;
import cn.easyplatform.web.utils.PageUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.zkoss.image.AImage;
import org.zkoss.image.Image;
import org.zkoss.lang.Objects;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Row;
import org.zkoss.zul.Rows;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class CheckgroupBuilder extends AbstractQueryBuilder<Checkgroup> implements Widget, Assignable,
        Labelable {

    public CheckgroupBuilder(OperableHandler mainTaskHandler, Checkgroup comp) {
        super(mainTaskHandler, comp);
    }

    public CheckgroupBuilder(ListSupport support, Checkgroup comp, Component anchor) {
        super(support, comp, anchor);
    }

    @Override
    public Component build() {
        if (me.getQuery() == null || Strings.isBlank(me.getQuery().toString()))
            throw new EasyPlatformWithLabelKeyException(
                    "component.property.not.found", "<checkgroup>", "query");
        if (Strings.isBlank(me.getFormat()))
            throw new EasyPlatformWithLabelKeyException(
                    "component.property.not.found", "<checkgroup>", "format");
        if (me.getCols() <= 0)
            throw new EasyPlatformWithLabelKeyException(
                    "component.property.not.found", "<checkgroup>", "cols");
        if (me.getType().equals("radio") && Strings.isBlank(me.getName()))
            throw new EasyPlatformWithLabelKeyException(
                    "component.property.not.found", "<checkgroup>", "name");

        PageUtils.checkAccess(main.getAccess(), me);
        me.setAttribute("$proxy", this);
        if (me.isImmediate())
            load();
        PageUtils.processEventHandler(main, me, anchor);
        return me;
    }

    protected void createModel(List<?> data) {
        me.setOddRowSclass("none");
        Component rows = new Rows();
        me.appendChild(rows);
        Component parent = null;
        int index = 0;
        for (Object fv : data) {
            if (index % me.getCols() == 0) {
                parent = new Row();
                rows.appendChild(parent);
            }
            Object[] fvs = (Object[]) fv;
            parent.appendChild(createCheckbox(fvs));
            index++;
        }
    }

    private Component createCheckbox(Object[] fv) {
        boolean isRaw = !(fv[0] instanceof FieldVo);
        Checkbox cbi = new Checkbox();
        cbi.setValue(isRaw ? fv[0] : ((FieldVo) fv[0]).getValue());
        cbi.setEvent(me.getEvent());
        cbi.setStyle(me.getItemStyle());
        cbi.setMold(me.getType());
        if (fv.length == 1) {
            Object val = isRaw ? fv[0] : ((FieldVo) fv[0]).getValue();
            cbi.setLabel(val == null ? "" : val
                    .toString());
        } else if (fv.length == 2) {
            Object val = isRaw ? fv[1] : ((FieldVo) fv[1]).getValue();
            cbi.setLabel(val == null ? "" : val
                    .toString());
        } else if (fv.length == 3) {
            Object val = isRaw ? fv[1] : ((FieldVo) fv[1]).getValue();
            cbi.setLabel(val == null ? "" : val
                    .toString());
            Object img = isRaw ? fv[2] : ((FieldVo) fv[2]).getValue();
            if (img != null) {
                if (img instanceof String) {
                    String str = (String) img;
                    if (str.startsWith("z-icon") || str.startsWith("fa fa-"))
                        cbi.setIconSclass(str);
                    else
                        cbi.setImage(str);
                } else if (img instanceof byte[]) {
                    try {
                        Image image = new AImage("", (byte[]) img);
                        cbi.setImageContent(image);
                    } catch (IOException e) {
                    }
                }
            }
        }
        cbi.setDisabled(me.isDisabled());
        cbi.addForward(Events.ON_CHECK, me, Events.ON_CHECK);
        return cbi;
    }

    @Override
    public void setValue(Object value) {
        if (value == null)
            return;
        Iterator<Component> itr = me.queryAll("checkbox").iterator();
        List<Component> cbs = new ArrayList<Component>();
        while (itr.hasNext()) {
            Component c = itr.next();
            Checkbox cb = (Checkbox) c;
            cb.setChecked(false);
            cbs.add(c);
        }
        if (cbs.isEmpty())
            return;
        if (me.getFormat().equalsIgnoreCase("json")) {
            setJsonValue((String) value, cbs);
        } else if (me.getFormat().equalsIgnoreCase("array")) {
            setArrayValue((Object[]) value, cbs);
        } else {
            setArrayValue(((String) value).split("\\" + me.getFormat()), cbs);
        }
        Object[] data = (Object[]) me.getAttribute("data");
        if (data != null) {
            Integer index = (Integer) me.getAttribute("index");
            if (index != null)
                data[index] = value;
        }
    }

    private void setArrayValue(Object[] data, List<Component> cbs) {
        for (Object v : data) {
            for (Component c : cbs) {
                Checkbox cb = (Checkbox) c;
                if (Lang.equals(cb.getValue(), v)) {
                    cb.setChecked(true);
                    break;
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    private void setJsonValue(String data, List<Component> cbs) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> map = mapper.readValue(data, Map.class);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                for (Component c : cbs) {
                    Checkbox cb = (Checkbox) c;
                    if (Objects.equals(cb.getValue(), entry.getKey())) {
                        cb.setChecked(entry.getValue().equalsIgnoreCase(
                                "true"));
                        break;
                    }
                }
            }
            mapper = null;
        } catch (Exception ex) {
            throw new IllegalArgumentException("<checkgroup>  value");
        }
    }

    @Override
    public Object getValue() {
        Iterator<Component> itr = me.queryAll("checkbox").iterator();
        List<Object> data = new ArrayList<Object>();
        while (itr.hasNext()) {
            Checkbox cb = (Checkbox) itr.next();
            if (cb.isChecked())
                data.add(cb.getValue());
        }
        if (me.getFormat().equalsIgnoreCase("json")) {
            Iterator<Object> it = data.iterator();
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            while (it.hasNext()) {
                sb.append("\"").append(itr.next()).append("\":\"true\"");
                if (it.hasNext())
                    sb.append(",");
            }
            sb.append("}");
            return sb.toString();
        } else if (me.getFormat().equalsIgnoreCase("array")) {
            Object[] value = new Object[data.size()];
            return data.toArray(value);
        } else {
            Iterator<Object> it = data.iterator();
            StringBuilder sb = new StringBuilder();
            while (it.hasNext()) {
                sb.append(it.next());
                if (it.hasNext())
                    sb.append(me.getFormat());
            }
            return sb.toString();
        }
    }

    @Override
    public String getLabel() {
        Iterator<Component> itr = me.queryAll("checkbox").iterator();
        StringBuilder sb = new StringBuilder();
        while (itr.hasNext()) {
            Checkbox cb = (Checkbox) itr.next();
            if (cb.isChecked()) {
                sb.append(cb.getLabel());
                if (itr.hasNext())
                    sb.append(me.getFormat());
            }
        }
        return sb.toString();
    }

    @Override
    public void reload(Component me) {
        me.getChildren().clear();
        load();
    }
}
